//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/dao/home_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/home/column_position_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/course/course_chapter_model.dart';
import 'package:hktk_app/util/dao_util.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/home/recommend_expandable_widget.dart';
// import 'package:hktk_app/widget/subject/purchase_tips_widget.dart';

/// 更多视频内容显示
class MoreVideoPage extends StatefulWidget {
  /// 栏目id
  final String columnId;

  /// 科目id
  final int? categoryId;

  /// 栏目名称
  final String? columnName;

  const MoreVideoPage({
    super.key,
    required this.columnId,
    this.categoryId,
    this.columnName,
  });

  @override
  State<MoreVideoPage> createState() => _MoreVideoPageState();
}

class _MoreVideoPageState extends State<MoreVideoPage> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关视频数据
  late List<CourseChapterModel> _list;

  /// 第一次执行方法
  late bool _init;

  /// 栏目id
  late String _columnId;

  /// 是否显示未购买提示
  late bool _showTips;

  /// 刷新方法执行，true：刷新状态，false：不是刷新状态
  late bool _refresh;

  /// 监听课程返回
  late StreamSubscription<EventCourseDetailBack> _eventCourseBack;

  @override
  void initState() {
    super.initState();

    _list = [];
    _init = true;
    _columnId = widget.columnId;
    _showTips = false;
    _futureInit = _initData();
    _refresh = false;

    // 监听课程页面返回
    _eventCourseBack = eventBus.on<EventCourseDetailBack>().listen((event) {

      _refreshFun();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventCourseBack.cancel();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          if (_init) {
            // 页面创建完成将_init转为false,只执行一次
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              _init = false;
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      // 判断是否需要章节加载对应的栏目id
      if (_columnId == "") {
        // 根据科目获取对应栏目
        List<ColumnModel> list = await HomeDao.columnByCategory(
          categoryId: widget.categoryId!,
          groupId: getGroupId(),
          columnEnum: ColumnPositionEnum.jgqy,
        );
        for (ColumnModel model in list) {
          if (model.name == widget.columnName) {
            _columnId = model.id!;
            break;
          }
        }
        if (_columnId == "") {
          map["suc"] = true;
          return map;
        }
      }
      // 根据栏目获取对应的课程数据
      DataModel dataModel = dataUtilComm.dataModel;
      _list = await CourseDao.listByColumn(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        columnId: _columnId,
      );

      // 获取是否购买
      if (widget.columnId == "") {
        for (CourseChapterModel model in _list) {
          if (model.free == false) {
            _showTips = true;
            break;
          }
        }
      }

      // 判断是否是刷新状态，刷新状态循环等待子集刷新完成
      if (_refresh) {
        _refresh = false;
        int i = 0;
        while (true) {
          i++;
          bool state = dataUtilComm.chapterRefreshState.getRefreshComplete();
          if (state) {
            break;
          }
          if (i >= 20) {
            throw DaoException(msg: "获取超时，请重试", code: -1);
          }
          await Future.delayed(const Duration(seconds: 3));
        }
      }

      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示
  Widget _content() {
    return Stack(
      children: [

        _contentItem(),
        if (_showTips)
          // PurchaseTipsWidget(
          //   columnId: _columnId,
          // ),
          Text("PurchaseTipsWidget")

      ],
    );
  }

  /// 章节练习内容显示方法
  _contentItem() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12),
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: colorWhite1,
        // color: colorBlack1,
        borderRadius: BorderRadius.all(Radius.circular(20)),
      ),
      child: _listItem(),
    );
  }

  /// 滑动组件显示
  Widget _listItem() {
    if (_list.isNotEmpty) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: _list.length + 1,
        ),
      );
    } else {
      return Center(
        child: Text(
          "暂无数据",
          style: FontUtil.fontGrey1(32),
        ),
      );
    }
  }

  /// 内容显示
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _list.length) {
      CourseChapterModel model = _list[index];
      return RecommendExpandableWidget(
        model: model,
        columnId: _columnId,
        free: model.free!,
        opening: index == 0 && _init,
        init: _init,
      );
    } else {
      return hiSpace(height: 80);
    }
  }

  /// 刷新当前页面方法
  void _refreshFun() {
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    _refresh = true;
    // 发送刷新通知
    eventBus.fire(EventCourseRefresh());
    // 刷新方法
    _initData().then((Map<String, dynamic> map) {
      ToastUtil.loadingBoxRemove();
      if (!map["suc"]) {
        ToastUtil.show(context: _context, msg: map["msg"]);
      } else {
        setState(() {});
      }
    });
  }
}
